package cn.relx.pet.service.impl;

import cn.relx.pet.domain.PetType;
import cn.relx.pet.mapper.PetTypeMapper;
import cn.relx.pet.service.IPetTypeService;
import cn.relx.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author relx
 * @since 2022-10-28
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> tree() {
        //查询出所有的部门数据
        List<PetType> typeList = petTypeMapper.findAll();
        //将集合数据转换为hashmap
        Map<Long, PetType> allmap = typeList.stream().collect(Collectors.toMap(PetType::getId, item -> item));
        List<PetType> petTypes = new ArrayList<>();
        for (PetType petType : typeList) {
            if(petType.getPid() == null){
                petTypes.add(petType);
            } else {
                PetType type = allmap.get(petType.getPid());
                if(petType != null){
                    List<PetType> children = type.getChildren();
                    children.add(petType);
//                    petType.getChildren().add(petType);
                }
            }
        }
        return petTypes;
    }
}
